package main

import (
	"fmt"

	"github.com/golang-jwt/jwt/v5"
)

type UserClaim struct {
	Identity string `json:"identity"`
	Name     string `json:"name"`
	jwt.RegisteredClaims
}

var myKey = []byte("gin-gorm-key")

func GenerateToken() string {
	userClaim := &UserClaim{
		Identity:         "user_1",
		Name:             "Get",
		RegisteredClaims: jwt.RegisteredClaims{},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaim)
	tokenString, err := token.SignedString(myKey)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(tokenString)
	return tokenString
}

func AnalyseToken(tokenString string) {
	parsedToken, err := jwt.ParseWithClaims(tokenString, &UserClaim{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return myKey, nil
	})

	if err != nil {
		fmt.Println("Error parsing token:", err)
		return
	}

	if claims, ok := parsedToken.Claims.(*UserClaim); ok && parsedToken.Valid {
		fmt.Println("Token is valid!")
		fmt.Printf("Identity: %s\n", claims.Identity)
		fmt.Printf("Name: %s\n", claims.Name)
	} else {
		fmt.Println("Invalid token!")
	}
}

func main() {
	token := GenerateToken()
	AnalyseToken(token)
}
